import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchAddFavoritesBallSlice, fetchDeleteFavoritesBallSlice, fetchGetFavoritesBallSlice } from './favorites.actions';

interface IItemFavoriteBall {
        id: number,
        name: string,
        image: string,
        price: number,
        count: number,
        title: string,
        description: string,
        favorite: false,
        user: {
            email: string,
            fullName: string,
            id: number
    }
}

interface IBallsFavorite {
    favoritesBalls: IItemFavoriteBall[],
	loading: boolean,
	errors: null,
	success: boolean 
}

const initialState: IBallsFavorite = {
	favoritesBalls: [],
	loading: false,
	errors: null,
	success: false
};

export const addFavoritesSlice = createSlice({
	name: 'addFavoriteBall',
	initialState,
	reducers: {
	},
	extraReducers: (builder) => {
		builder.addCase(fetchAddFavoritesBallSlice.pending, (state) => {
			state.success = false;
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchAddFavoritesBallSlice.fulfilled,
			(state, action) => {
				state.favoritesBalls = [...state.favoritesBalls, action.payload];
				state.loading = false;
				state.success = true;
			}
		);
		builder.addCase(fetchAddFavoritesBallSlice.rejected, (state, action) => {
			// state.loading = true;
			state.errors = action.error.message;
		});
		builder.addCase(fetchGetFavoritesBallSlice.pending, (state) => {
			state.loading = true;
			state.errors = null;
			state.success = false;

		});
		builder.addCase(
			fetchGetFavoritesBallSlice.fulfilled,
			(state, action: PayloadAction<IItemFavoriteBall[]>) => {
				console.log('избранные мячики из favorite.slice.ts', action.payload);
				state.favoritesBalls = action.payload;
				state.loading = false;
			}
		);
		builder.addCase(fetchGetFavoritesBallSlice.rejected, (state, action) => {
			
			// state.loading = true;
			console.log('ошибка по избранному', action);
			state.errors = action.error.message;
		});
		builder.addCase(fetchDeleteFavoritesBallSlice.pending, (state) => {
			state.success = false;
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchDeleteFavoritesBallSlice.fulfilled,
			(state, action: PayloadAction<number>) => {
				console.log('избранные после удаления', action.payload);
				state.favoritesBalls = state.favoritesBalls.filter(item => item.id === action.payload);
				state.loading = false;
				state.success = true;
			}
		);
		builder.addCase(fetchDeleteFavoritesBallSlice.rejected, (state, action) => {
			// state.loading = true;
			console.log('ошибка по избранному', action);
			state.errors = action.error.message;
		});
	}
});

export default addFavoritesSlice.reducer;

